package com.dkm.orproject.dkmoa.action.flow;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaDimissionFlow;
import com.dkm.orproject.dkmoa.domain.OaGradeFlow;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.service.flow.OaGradeFlowService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import io.swagger.annotations.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  @ClassName : OaGradeFlowAction  //类名
 *  @Description : 工资定级流程  //描述
 *  @Author : 石智诚  //作者
 *  @Date: 2020-10-14 10:54  //时间
 */
@RestController
@Api(tags="工资定级接口文档")
@RequestMapping("/OaGradeFlowAction")
public class OaGradeFlowAction {

    /**
     * 转正流程服务接口
     */
    @Resource


    OaGradeFlowService oaGradeFlowService;
    /**
     * 工具类
     */
    @Resource
    Tools tools;
    /**
     * 回调值
     */
    int row=0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 分页查询
     * @param gradeFlow 定级流程模型 用于条件查询
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param page 当前页数
     * @param limit 显示的行数
     * @return 转正流程集
     */
    @ApiOperation(value = "员工薪资定级查询接口", notes = "员工薪资定级查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeName",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String,Object> findAll(OaGradeFlow gradeFlow,
                                      String startTime,
                                      String endTime,
                                      Integer page,
                                      Integer limit,
                                      HttpServletRequest request){
        try{
            List<OaGradeFlow> dataDictionaries=oaGradeFlowService.findAll(gradeFlow,page,limit,startTime,endTime);
            Long rowCount=oaGradeFlowService.rowCount(gradeFlow,startTime,endTime);
            return Tools.maps(dataDictionaries,rowCount);
        }catch (Exception e){
            addErrorLog(request,"转正流程分页查询",e);
        }
        return null;

    }


    /**
     * 根据id查询
     * @param id 转正流程主键
     * @return 转正流程模型
     */
    @ApiOperation(value = "根据id查询员工薪资定级接口", notes = "根据id查询员工薪资定级接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "定级流程Id",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @GetMapping("findById/{id}")
    public OaGradeFlow findById(@PathVariable("id") Long id, HttpServletRequest request){
        try{
            return oaGradeFlowService.selectByPrimaryKey(id);
        }catch (Exception e){
            addErrorLog(request,"转正流程id查询",e);
        }
        return null;
    }
    /**
     * 定级流程起草节点
     * @param gradeFlow 薪资定级
     * @param request 服务器请求 用于得到登陆人信息
     * @return 回调函数
     */
    @ApiOperation(value = "定级流程起草节点接口", notes = "定级流程起草节点接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeFlow",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @PostMapping("addGrade")
    public int addGrade(OaGradeFlow gradeFlow, HttpServletRequest request){
        rowMap(request);
        try{
            return oaGradeFlowService.insert(gradeFlow,personnel);
        }catch (Exception e){
            addErrorLog(request,"人员交接工作起草节点",e);
            return 500;
        }
    }

    /**
     * 行政部填写
     * @param gradeFlow 薪资定级
     * @param request 服务器请求 用于得到登陆人信息
     * @return 回调函数
     */
    @ApiOperation(value = "行政部填写接口", notes = "定级流程行政部填写接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeFlow",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @PostMapping("staffingWrite")
    public int staffingWrite(OaGradeFlow gradeFlow, HttpServletRequest request){
        rowMap(request);
        try{
            return oaGradeFlowService.staffingWrite(gradeFlow,personnel);
        }catch (Exception e){
            addErrorLog(request,"行政部填写节点",e);
            return 500;
        }
    }

    /**
     * 部门审核
     * @param gradeFlow 薪资定级
     * @param request 服务器请求 用于得到登陆人信息
     * @return 回调函数
     */
    @ApiOperation(value = "部门审核接口", notes = "部门审核接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeFlow",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @PostMapping("departMentPass")
    public int departMentPass(OaGradeFlow gradeFlow, HttpServletRequest request){
        rowMap(request);
        try{
            return oaGradeFlowService.departmentPass(gradeFlow,personnel);
        }catch (Exception e){
            addErrorLog(request,"部门审核节点",e);
            return 500;
        }
    }

    /**
     * 部门领导不通过
     * @param request 服务器请求
     * @param flow 审核信息
     * @return 回调函数
     */
    @ApiOperation(value = "部门领导不通过接口", notes = "部门领导不通过接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeFlow",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @PostMapping("departMentNoPass")
    public Map<String,Object> departMentNoPass(HttpServletRequest request,OaGradeFlow flow,String formReason){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            row=oaGradeFlowService.departmentNoPass(flow,personnel,formReason);
            log.setLogTitle("部门审核不通过");
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(flow).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"部门审核不通过",e);
        }
        return map;
    }
    /**
     * 行政部审核
     * @param gradeFlow 薪资定级ID
     * @param request 服务器请求 用于得到登陆人信息
     * @return 回调函数
     */
    @ApiOperation(value = "部门领导不通过接口", notes = "部门领导不通过接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeFlow",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @PostMapping("staffingPass")
    public int staffingPass(OaGradeFlow gradeFlow, HttpServletRequest request){
        rowMap(request);
        try{
            return oaGradeFlowService.staffingPass(gradeFlow,personnel);
        }catch (Exception e){
            addErrorLog(request,"行政部审核节点",e);
            return 500;
        }
    }
    /**
     * 行政部领导不通过
     * @param request 服务器请求
     * @param flow 审核信息
     * @return 回调函数
     */
    @ApiOperation(value = "部门领导不通过接口", notes = "部门领导不通过接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeFlow",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })

    @UserLoginToken
    @PostMapping("staffingNoPass")
    public Map<String,Object> staffingNoPass(HttpServletRequest request,OaGradeFlow flow,String formReason){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            row=oaGradeFlowService.staffingNoPass(flow,personnel,formReason);
            log.setLogTitle("行政部审核不通过");
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(flow).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"行政部审核不通过",e);
        }
        return map;
    }
    /**
     * 总经理审核
     * @param gradeFlow 薪资定级ID
     * @param request 服务器请求 用于得到登陆人信息
     * @return 回调函数
     */
    @ApiOperation(value = "部门领导不通过接口", notes = "部门领导不通过接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeFlow",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @PostMapping("exPass")
    public int exPass( OaGradeFlow gradeFlow, HttpServletRequest request){
        rowMap(request);
        try{
            return oaGradeFlowService.executivePass(gradeFlow,personnel);
        }catch (Exception e){
            addErrorLog(request,"总经理+审核节点",e);
            return 500;
        }
    }
    /**
     * 总经理领导不通过
     * @param request 服务器请求
     * @param flow 审核信息
     * @return 回调函数
     */
    @ApiOperation(value = "部门领导不通过接口", notes = "部门领导不通过接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeFlow",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @PostMapping("exNoPass")
    public Map<String,Object> exNoPass(HttpServletRequest request,OaGradeFlow flow,String formReason){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            row=oaGradeFlowService.executiveNoPass(flow,personnel,formReason);
            log.setLogTitle("总经理审核不通过");
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(flow).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"总经理审核不通过",e);
        }
        return map;
    }
    /**
     * 增加定级流程
     * @param flow  流程
     * @param request 请求
     * @return 成功的数量
     */
    @ApiOperation(value = "增加定级流程接口", notes = "增加定级流程接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "affirmTime",value = "离职流程名称（模糊）",dataType = "Date",paramType = "path"),
            @ApiImplicitParam(name = "personnelId", value = "当前Id", required = true, dataType = "Long",paramType = "path"),

    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @PostMapping("add")
    public Map<String, Object> add(OaGradeFlow flow, HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(flow.getPersonnelId())) {
                tools.rowMap(map,0,log);
            }
        try {
            row=oaGradeFlowService.insert(flow,personnel);
            log.setLogTitle("定级流程新增");
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(flow).toString());
            tools.rowMap(map,row,log);
        }catch (Exception e){
            e.printStackTrace();
            log.setLogTitle("定级流程操作");
            log.setLogType("0");
            log.setLogBody(e.getLocalizedMessage());
            tools.errorMap(map,log);
        }
        return map;
    }


    /**
     * 根据定级id删除
     * @param id 转正流程id
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "根据定级id删除接口", notes = "根据定级id删除接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "定级id",dataType = "Integer",paramType = "path"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @DeleteMapping("deleteById/{id}")
    public Map<String,Object> deleteById(@PathVariable(value = "id",required = false)Long id,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            OaGradeFlow flow=oaGradeFlowService.selectByPrimaryKey(id);
            row=oaGradeFlowService.deleteByPrimaryKey(id);
            log.setLogTitle("转正流程删除");
            log.setLogBody(JSON.toJSON(flow).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"转正流程删除",e);
        }
        return map;
    }

    @UserLoginToken
    @DeleteMapping("deleteAll")
    public Map<String,Object> deleteAll(@RequestParam(value = "ids[]",required = false) Long[] ids,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }
        try{
            List<Long> list=Arrays.asList(ids);
            List<OaGradeFlow> oaGradeFlows = oaGradeFlowService.selectAll(list);
            row=oaGradeFlowService.deleteByAll(list);
            log.setLogTitle("薪资定级流程删除");
            log.setLogBody(JSON.toJSON(oaGradeFlows).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"薪资定级流程删除",e);
        }
        return map;
    }



    /**
     * 优化代码
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }
    /**
     * 查询报错日志新增
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        e.printStackTrace();
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        log=new OaLog();
        log.setLogType("0");
        log.setLogBody(e.getLocalizedMessage());
        log.setLogTitle(title);
        log.setLogIp(request.getRemoteAddr());
        if(ObjectUtils.isEmpty(personnel)){
            log.setCreatedBy(personnel.getPersonnelName());
        }
        tools.errorMap(log);
    }
    /**
     * 日期格式化
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
